<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.search"
          placeholder="请输入用户名/手机号搜索"
          clearable
          style="width: 200px"
          @keyup.enter="handleFilter"
        />
        <el-input
          v-model="listQuery.user_id"
          placeholder="请输入用户ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleFilter"
        />
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="primary" @click="handleCreate">新增用户</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        stripe
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="user_id" label="ID" width="80" align="center" />
        <el-table-column prop="nick_name" label="昵称" min-width="120" />
        <el-table-column prop="mobile" label="手机号" min-width="120">
          <template #default="scope">
            {{
              userStore.isTest ? maskMobile(scope.row.mobile) : scope.row.mobile
            }}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="100" />
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column
          prop="usage_count"
          label="使用次数"
          width="100"
          align="center"
        />
        <el-table-column label="注册时间" width="160" align="center">
          <template #default="scope">
            <span>{{ formatDate(scope.row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="listQuery.page"
          :page-size="listQuery.per_page"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增用户' : '编辑用户'"
      v-model="dialogFormVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="昵称" prop="nick_name">
          <el-input v-model="form.nick_name" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="积分" prop="points">
          <el-input-number v-model="form.points" :min="0" />
        </el-form-item>
        <el-form-item label="使用次数" prop="usage_count">
          <el-input-number v-model="form.usage_count" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserList, addUser, updateUser, deleteUser } from "@/api/users";
import { useUserStore } from "@/store/user";

const userStore = useUserStore();

// 列表数据
const list = ref([]);
const total = ref(0);
const listLoading = ref(false);
const dialogFormVisible = ref(false);
const dialogStatus = ref("");
const formRef = ref(null);

// 查询参数
const listQuery = reactive({
  page: 1,
  per_page: 20,
  search: "",
  user_id: "",
});

// 表单数据
const form = reactive({
  user_id: undefined,
  nick_name: "",
  mobile: "",
  points: 0,
  usage_count: 0,
});

// 表单验证规则
const rules = {
  nick_name: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
};

// 获取用户列表
const getList = async () => {
  listLoading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: listQuery.page,
      per_page: listQuery.per_page,
    };

    if (listQuery.search) {
      params.search = listQuery.search;
    }

    if (listQuery.user_id) {
      params.user_id = listQuery.user_id;
    }

    const res = await getUserList(params);
    list.value = res.data.items || [];
    total.value = res.data.total || 0;
  } catch (error) {
    console.error("获取用户列表失败", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    listLoading.value = false;
  }
};

// 搜索过滤
const handleFilter = () => {
  listQuery.page = 1;
  getList();
};

// 处理每页显示数量改变
const handleSizeChange = (val) => {
  listQuery.per_page = val;
  getList();
};

// 处理页码改变
const handleCurrentChange = (val) => {
  listQuery.page = val;
  getList();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.user_id = undefined;
  form.nick_name = "";
  form.mobile = "";
  form.points = 0;
  form.usage_count = 0;
};

// 新建用户
const handleCreate = () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("add:user")) {
    ElMessage.warning("测试账号不能新增用户");
    return;
  }

  resetForm();
  dialogStatus.value = "create";
  dialogFormVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("edit:user")) {
    ElMessage.warning("测试账号不能编辑用户");
    return;
  }

  resetForm();
  Object.assign(form, row);
  dialogStatus.value = "update";
  dialogFormVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能修改用户信息");
    return;
  }

  try {
    await formRef.value.validate();

    if (dialogStatus.value === "create") {
      // 创建用户
      await addUser(form);
      ElMessage.success("用户创建成功");
    } else {
      // 更新用户
      await updateUser(form.user_id, form);
      ElMessage.success("用户更新成功");
    }

    dialogFormVisible.value = false;
    getList();
  } catch (error) {
    console.error("保存用户失败", error);
    ElMessage.error("保存用户失败");
  }
};

// 删除用户
const handleDelete = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("delete:user")) {
    ElMessage.warning("测试账号不能删除用户");
    return;
  }

  ElMessageBox.confirm(
    `确定要删除用户 ${row.nick_name || row.user_id} 吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        await deleteUser(row.user_id);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        console.error("删除用户失败", error);
        ElMessage.error("删除用户失败");
      }
    })
    .catch(() => {
      // 取消删除操作
    });
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

// 页面加载时获取列表
onMounted(() => {
  getList();
});
</script>

<style scoped>
.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
